package com.rex.sample.thread;

import com.rex.sample.util.SpringContextHolder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.orm.hibernate4.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * Created by Lidong on 2015-11-13
 * A thread version of <code>OpenSessionInViewFilter</code>
 */
public abstract  class AbstractSpringThreadBase implements Runnable {

    SessionFactory sessionFactory = (SessionFactory) SpringContextHolder.getBean("sessionFactory");

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p/>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {

        Session session = sessionFactory.openSession();
        SessionHolder sessionHolder = new SessionHolder(session);
        TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
        try{

            trueRun();

        }finally {
            sessionHolder = (SessionHolder)TransactionSynchronizationManager.unbindResource(sessionFactory);
            SessionFactoryUtils.closeSession(sessionHolder.getSession());
        }
    }

    /**
     * Subclass must implement this method
     */
    public abstract void trueRun();
}
